﻿namespace EntityAccessImp;

public class DraftServices : IDraftServices
{
    public ISqlSugarClient DB { get; set; }

    public IAnnotationServices AnnotationServices { get; set; }

    public DraftServices(ISqlSugarClient sqlSugarClient, IAnnotationServices annotationServices)
    {
        DB = sqlSugarClient;
        AnnotationServices = annotationServices;
    }

    public async Task<AddResult<int>> AddDraftAsync(Draft draft)
    {
        ///添加Draft
        int r;
        try
        {
            r = await DB
                .Insertable(draft)
                .ExecuteReturnIdentityAsync();
        }
        catch (Exception e)
        {
            return new AddResult<int>()
            {
                StatusCode = Code.DBError,
                Message = "添加Draft失败",
                SourceException = e
            };
        }

        ///添加Draft名下的注记
        var annotations = draft.MapAnnotations;
        var ownerID = draft.OwnerID;
        var annoList = new List<Annotation>(annotations.Count);
        annotations.ForEach((item) => annoList.Add(item.ToAnnotation(r)));
        var addResult = await AnnotationServices.AddAnnotationsAsync(annoList);

        ///添加失败
        if (!addResult.Succeed)
            return new AddResult<int>()
            {
                StatusCode = addResult.StatusCode,
                Message = $"Draft添加成功，但是其名下的注记添加失败，详情：{addResult.Message}",
                SourceException = addResult.SourceException,
            };

        return new AddResult<int>()
        {
            StatusCode = Code.Succeed,
            Message = "添加Draft成功",
            NewKey = r,
        };
    }

    public async Task<DeleteResult> DeleteDraftAsync(int draftID)
    {
        try
        {
            int r = await DB
                .Deleteable<Draft>()
                .In(draftID)
                .ExecuteCommandAsync();
            return new DeleteResult()
            {
                StatusCode = Code.Succeed,
                Message = "删除Draft成功",
                ChangedColumnNum = r
            };
        }
        catch (Exception e)
        {
            return new DeleteResult()
            {
                StatusCode = Code.DBError,
                Message = "删除Draft失败",
                SourceException = e
            };
        }
    }

    public async Task<GetResult<Draft>> GetDeepCopyOf(int draftID)
    {
        var ans = await AnnotationServices.GetRelativeAnnotationsAsync(draftID);
        if (!ans.Succeed)
            return new GetResult<Draft>()
            {
                StatusCode = ans.StatusCode,
                Message = $"获取Draft深拷贝失败，详情：{ans.Message}",
                SourceException = ans.SourceException
            };

        var draftResult = await GetDraftAsync(draftID);
        if (!draftResult.Succeed)
            return new GetResult<Draft>()
            {
                StatusCode = ans.StatusCode,
                Message = $"获取Draft信息失败，详情：{draftResult.Message}",
                SourceException = draftResult.SourceException
            };

        var draft = draftResult.ResultObject;
        var georesult = ans.ResultObject;
        if (draft is null || georesult is null)
            return new GetResult<Draft>()
            {
                StatusCode = ans.StatusCode,
                Message = $"解析Draft信息失败",
            };

        var geolist = new List<Geometry>(georesult.Count);
        georesult.ForEach((item) => geolist.Add(item.FeatureInGeometry));
        draft.AddAnnotations(geolist);

        return new GetResult<Draft>()
        {
            Message = "获取成功",
            StatusCode = Code.Succeed,
            ResultObject = draft,
        };
    }

    public async Task<GetResult<Draft>> GetDraftAsync(int draftID)
    {
        try
        {
            var r = await DB
                .Queryable<Draft>()
                .InSingleAsync(draftID);
            return new GetResult<Draft>()
            {
                StatusCode = Code.Succeed,
                Message = "查询Draft成功",
                ResultObject = r
            };
        }
        catch (Exception e)
        {
            return new GetResult<Draft>()
            {
                StatusCode = Code.DBError,
                Message = "查询Draft失败",
                SourceException = e
            };
        }
    }

    public async Task<GetResult<List<Draft>>> GetRelativeDraftsAsync(int userAccount)
    {
        try
        {
            var r = await DB
                .Queryable<Draft>()
                .Where(it => it.OwnerID == userAccount)
                .ToListAsync();
            return new GetResult<List<Draft>>()
            {
                StatusCode = Code.Succeed,
                Message = "查询Drafts成功",
                ResultObject = r
            };
        }
        catch (Exception e)
        {
            return new GetResult<List<Draft>>()
            {
                StatusCode = Code.DBError,
                Message = "查询Drafts失败",
                SourceException = e
            };
        }
    }

    public async Task<AddResult<int>> UpdateDraftsAsync(Draft draft)
    {
        var delResult = await DeleteDraftAsync(draft.ID);
        if (!delResult.Succeed)
            return new AddResult<int>()
            {
                StatusCode = delResult.StatusCode,
                Message = $"删除旧Draft失败，详情：{delResult.Message}",
                SourceException = delResult.SourceException
            };

        var addResult = await AddDraftAsync(draft);
        if(!addResult.Succeed)
            return new AddResult<int>()
            {
                StatusCode = addResult.StatusCode,
                Message = $"删除旧Draft成功，但是创建新Draft失败，详情：{addResult.Message}",
                SourceException = addResult.SourceException
            };

        draft.ID = addResult.NewKey;
        return new AddResult<int>()
        {
            StatusCode = Code.Succeed,
            Message = "更新Draft成功",
            NewKey = addResult.NewKey
        };
    }
}
